import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class SimpleFileNio {

    public static void main(String[] args) throws Exception {

        RandomAccessFile accessFile = new RandomAccessFile("log/output.log","rw");
        FileChannel fileChannel = accessFile.getChannel();

        ByteBuffer byteBuffer = ByteBuffer.allocate(48);
        // 写入到 buffer中
        int bytesRead = fileChannel.read(byteBuffer);

        while (bytesRead != -1) {

            System.out.println("read:" + bytesRead);
            // flip方法将Buffer从写模式切换到读模式
            byteBuffer.flip();

            // 是否有元素
            while (byteBuffer.hasRemaining()) {
                System.out.print((char) byteBuffer.get());
            }
            // 清除缓冲区
            byteBuffer.clear();
            // 读取
            bytesRead = fileChannel.read(byteBuffer);
        }
        accessFile.close();
    }

}
